<?php

namespace app\index\controller;

use app\common\controller\Frontend;
use GatewayClient\Gateway;

use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Session;


class Taizhu extends Frontend
{

    protected $layout = 'default';
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize()
    {
        parent::_initialize();

    }

    /**
     * 首页-设备列表
     */
    // http://wu.test/index/taizhu
    public function index()
    {
        $deviceList = \app\admin\model\wu\Hjsb::all();
        $deviceList = collection($deviceList)->toArray();

        $this->view->assign('title', __('首頁'));
        $this->view->assign('deviceList', $deviceList);
        return $this->view->fetch();
    }

    /**
     * 命令收發
     */
    // http://wu.test/index/taizhu/command
    public function command()
    {
        $deviceid = $this->request->request('deviceid', 0);
        $device = \app\admin\model\wu\Hjsb::where("deviceid", $deviceid)->find();
        $device = $device->toArray();
        $this->view->assign('device', $device);

        $dataList = [];
//        $recordslist = \app\admin\model\wu\Hjsblog::where("hjsb_id", $device['id'])->order("id", "desc")->limit(10)->select();
//        $commandloglist = \app\admin\model\wu\Commandlog::where("deviceid", $deviceid)->order("id", "desc")->limit(10)->select();
//
//        foreach ($recordslist as $row) {
//            //AI-THINKER_71D4B6,FE01,0100*
//            $dataList[] = array(
//                'create_time' => $row->create_time,
//                'msg' => $device['name'] . " = " . $device['value'] . "," . $device['value2'],
//                'isRecevice' => 1
//            );
//        }
//
//        foreach ($commandloglist as $row) {
//            //FE99,0000*
//            $dataList[] = array(
//                'create_time' => $row->create_time,
//                'msg' => $row->content,
//                'isRecevice' => 0
//            );
//        }

        $sql = "select * from test where name like '%" . $deviceid . "%' order by id desc limit 100";
        $testlist = Db::query($sql);

        foreach ($testlist as $row) {
            $name = $row['name'];
            $name = substr($name, 35);
            $dataList[] = array(
                'create_time' => $row['create_time'],
                'msg' => $name,
                'isRecevice' => 1
            );
        }

//        $idArr = array_column($dataList, 'create_time');
//        array_multisort($idArr, SORT_DESC, $dataList);

        $this->assignconfig("deviceid", $deviceid);

        $this->view->assign('dataList', $dataList);
        $this->view->assign('title', __('命令收發'));
        return $this->view->fetch();
    }

    // http://wu.test/index/taizhu/sendmsg
    public function sendmsg($msgtype, $deviceid)
    {
        switch ($msgtype) {
            default:
            case 1:
                $msg = ">FE04,0100*";
                $type = "切換 A 組馬達";
                break;
            case 2:
                $msg = ">FE05,0040*";
                $type = "切換 B 組馬達";
                break;
        }

        if (!$this->send($deviceid, $msg)) {
            $this->error($type . '发送失败');
        }

        $this->success($type . "发送成功！");
    }

    public function send($deviceid, $msg)
    {
        try {
            Gateway::$registerAddress = '127.0.0.1:1240';
            $device = \app\admin\model\wu\Hjsb::where('deviceid', 'like', '%' . $deviceid . '%')->find();//前缀匹配

            $client_id = "";
            if (!empty($device)) {
                $client_id = $device['client_id'];
            }

            if (!empty($client_id)) {
                if (!Gateway::isOnline($client_id)) {
                    $device->isonline = 0;
                    $device->save();
                    $this->error($deviceid . '不在线！');
                }

                $commandlog = new \app\admin\model\wu\Commandlog();
                $commandlog->deviceid = $deviceid;
                $commandlog->content = $msg;
                $commandlog->save();
                Gateway::sendToClient($client_id, $msg);
                return true;
            }

        } catch (\Exception $e) {
            return false;
        } catch (\Error $e) {
            return false;
        }

        return false;
    }

}
